/*
 * Copyright (c) 2023-2024 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.mybatis.injector.methods;

import com.baomidou.mybatisplus.core.injector.methods.SelectList;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;

/**
 * selectList(ew)
 *
 * @author elsfs
 */
public class SelectListIgnoreLogicDelete extends SelectList {
  private static final String METHOD_NAME = "selectListIgnoreLogicDelete";

  /** 构造方法 */
  public SelectListIgnoreLogicDelete() {
    super(METHOD_NAME);
  }

  /**
   * EntityWrapper方式获取select where
   *
   * @param newLine 是否提到下一行
   * @param table 表信息
   * @return String
   */
  @Override
  protected String sqlWhereEntityWrapper(boolean newLine, TableInfo table) {
    String andSqlSegment =
        SqlScriptUtils.convertIf(
            String.format(" AND ${%s}", WRAPPER_SQLSEGMENT),
            String.format("_sgEs_ and %s", WRAPPER_NONEMPTYOFNORMAL),
            true);
    String sqlScript = table.getAllSqlWhere(true, true, true, WRAPPER_ENTITY_DOT);
    sqlScript =
        SqlScriptUtils.convertIf(sqlScript, String.format("%s != null", WRAPPER_ENTITY), true);
    String lastSqlSegment =
        SqlScriptUtils.convertIf(
            String.format(" ${%s}", WRAPPER_SQLSEGMENT),
            String.format("_sgEs_ and %s", WRAPPER_EMPTYOFNORMAL),
            true);
    String sgEs = "<bind name=\"_sgEs_\" value=\"ew.sqlSegment != null and ew.sqlSegment != ''\"/>";
    sqlScript =
        SqlScriptUtils.convertIf(
            sgEs + NEWLINE + sqlScript + NEWLINE + andSqlSegment + NEWLINE + lastSqlSegment,
            String.format("%s != null", WRAPPER),
            true);
    sqlScript =
        SqlScriptUtils.convertWhere(table.getLogicDeleteSql(false, false) + NEWLINE + sqlScript);
    return newLine ? NEWLINE + sqlScript : sqlScript;
  }
}
